package cn.edu.nju.software.android.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class AsyncImageLoader {
	private static HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

	public AsyncImageLoader() {
	}

	public Drawable loadDrawable(final Context context, final Handler failureHandler, final String imageUrl,final ImageView imageView, final ImageCallback imageCallback, final int reqWidth, final int reqHeight){
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> reference = imageCache.get(imageUrl);  
			Drawable drawable = reference.get();  
			if(drawable != null)  
			{  
				return drawable;  
			}  
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageView,imageUrl);
			}
		};
		//建立新一个新的线程下载图片
		new Thread() {
			@Override
			public void run() {
				Drawable drawable = loadImageFromUrl(context, failureHandler, imageUrl, reqWidth, reqHeight);
				if(drawable == null)
					return;
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	public static Drawable loadImageFromUrl(Context context,Handler failureHandler, String url, int reqWidth, int reqHeight){
		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo moblie = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (mWifi.isConnected() || moblie.isConnected() ) {
			if(ping("http://www.baidu.com")){
				URL m;
				InputStream i = null;
				try {
					m = new URL(url);
					i = (InputStream) m.getContent();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				Drawable d  = null;
				if(reqHeight == 0){
					d = Drawable.createFromStream(i, "src");
				}else{
					String fileName = LocalFileHelper.savePic(context, i);
					Bitmap bitmap = ImageUtil.decodeSampledBitmapFromFile(context.getFilesDir() + "/" + fileName, reqWidth, reqHeight);
					context.deleteFile(fileName);
					if(bitmap == null)
						return null;
					d = new BitmapDrawable(bitmap);
				}
				return d;
			}else{
				return null;
			}
		}else{
			failureHandler.sendEmptyMessage(0);
			return null;
		}
	}

	//回调接口
	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl);
	}

	public static HashMap<String, SoftReference<Drawable>> getImageCache() {
		return imageCache;
	}

	public static void setImageCache(
			HashMap<String, SoftReference<Drawable>> imageCache) {
		AsyncImageLoader.imageCache = imageCache;
	}

	private static boolean ping(String u) { 
		try {
			URL url = new URL(u);
			HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
			urlc.setConnectTimeout(500); // Time is in Milliseconds to wait for ping response
			urlc.connect();
			if (urlc.getResponseCode() == 200) {
				return true;
			}else{
				return false;
			}
		}catch (MalformedURLException e1){
			return false;
		}catch (IOException e){
			return false;
		}
	}

}
